import 'dart:convert';

import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:travel/model/city.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class CityController extends GetxController {
  double susItemHeight = 35.h;
  RxString city = '北海市'.obs;
  RxList<CityDataModel> dataList = RxList([]);
  RxList<CityModel> visitList = RxList([]);
  String imgFavorite = ToolsUtils.getImgPath('ic_favorite');

  @override
  void onInit() {
    super.onInit();
    visitList.add(CityModel(name: '北京市', tagIndex: '★'));
    visitList.add(CityModel(name: '广州市', tagIndex: '★'));
    visitList.add(CityModel(name: '成都市', tagIndex: '★'));
    visitList.add(CityModel(name: '深圳市', tagIndex: '★'));
    visitList.add(CityModel(name: '杭州市', tagIndex: '★'));
    visitList.add(CityModel(name: '武汉市', tagIndex: '★'));
    loadData();
  }

  void loadData() async {
    //加载城市列表
    rootBundle.loadString('assets/data/city.json').then((value) {
      dataList.clear();
      var mapData = <String, dynamic>{};
      List list = json.decode(value);
      for (var e in list) {
        List city = e['city'];
        for (var c in city) {
          var name = c['name'];
          String pinyin = PinyinHelper.getPinyinE(name);
          String tag = pinyin.substring(0, 1).toUpperCase();
          if (mapData[tag] != null) {
            mapData[tag].add(CityModel(name: name, namePinyin: pinyin, tagIndex: tag));
          } else {
            mapData[tag] = [CityModel(name: name, namePinyin: pinyin, tagIndex: tag)];
          }
        }
      }
      mapData.forEach((name, value) => dataList.add(CityDataModel(name: name, children: value)));
      handleDataList(dataList);
    });
  }

  void handleDataList(RxList<CityDataModel> dataList) {
    if (dataList.isEmpty) return;
    for (int i = 0, length = dataList.length; i < length; i++) {
      String pinyin = dataList[i].name;
      String tag = pinyin.substring(0, 1).toUpperCase();
      dataList[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        dataList[i].tagIndex = tag;
      } else {
        dataList[i].tagIndex = '#';
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(dataList);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(dataList);

    // add header.
    dataList.insert(0, CityDataModel(name: 'header', tagIndex: imgFavorite));
  }
}

class CityView extends GetView<CityController> {
  const CityView({super.key});

  @override
  Widget build(BuildContext context) {
    return buildWidget(context);
  }

  Widget buildWidget(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: true,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Icon(
            Icons.arrow_back_ios,
            color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
            size: 20.w,
          ),
        ),
        leadingWidth: 40.w,
        title: Container(
            height: 38.h,
            padding: EdgeInsets.only(left: 10.w, right: 15.w),
            decoration: BoxDecoration(
                border:
                    Border.all(color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478)),
                borderRadius: BorderRadius.all(const Radius.circular(20).w)),
            child: Obx(() => TextField(
                  controller: ToolsUtils.editingController(controller.city.value),
                  cursorWidth: 2.0,
                  cursorRadius: const Radius.circular(2),
                  cursorColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                  style: StylesUtils.customTextStyle(fontSize: 15.sp, color: ColorsUtils.color3333),
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.search_sharp, size: 25.sp),
                    prefixIconColor: Colors.black54,
                    prefixIconConstraints: BoxConstraints.expand(width: 35.w),
                    border: InputBorder.none,
                    focusedBorder: InputBorder.none,
                    hintText: '搜索目的地',
                    contentPadding: EdgeInsets.symmetric(vertical: 12.h),
                    isCollapsed: true,
                    isDense: true,
                    hintStyle: StylesUtils.customTextStyle(
                      color: ColorsUtils.color9999,
                    ),
                    suffixIcon: ToolsUtils.assetImageSvg('u595.svg', width: 18.w, height: 18.h),
                    suffixIconConstraints: BoxConstraints.expand(width: 18.w, height: 18.h),
                    constraints: BoxConstraints(maxHeight: 38.h),
                  ),
                  onChanged: (String keyword) {
                    controller.city.value = keyword;
                  },
                ))),
        actions: [
          Container(
            constraints: BoxConstraints.expand(width: 60.w, height: 38.h),
            margin: EdgeInsets.only(left: 15.w, right: 10.w),
            alignment: Alignment.center,
            child: Text('搜索', style: StylesUtils.customTextStyle(color: ColorsUtils.color3478)),
          )
        ],
        scrolledUnderElevation: 0,
        systemOverlayStyle: SystemUiOverlayStyle.dark,
        elevation: 0,
      ),
      body: Obx(() => Padding(
          padding: EdgeInsets.symmetric(vertical: 10.w),
          child: AzListView(
            data: controller.dataList,
            itemCount: controller.dataList.length,
            itemBuilder: (BuildContext context, int index) {
              if (index == 0) return buildHeader();
              CityDataModel model = controller.dataList[index];
              return getListDataItem(context, model);
            },
            susItemHeight: controller.susItemHeight,
            susItemBuilder: (BuildContext context, int index) {
              CityDataModel model = controller.dataList[index];
              String tag = model.getSuspensionTag();
              if (index == 0) {
                return Container();
              }
              return getSusDataItem(context, tag, susHeight: controller.susItemHeight);
            },
            indexBarData: SuspensionUtil.getTagIndexList(controller.dataList),
            indexBarOptions: IndexBarOptions(
              needRebuild: true,
              color: Colors.transparent,
              downColor: const Color(0xFFEEEEEE),
              textStyle: StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 13.sp),
              selectTextStyle: StylesUtils.customTextStyle(color: ColorsUtils.color3478),
              localImages: [controller.imgFavorite], //local images.
            ),
          ))),
    );
  }

  List<Widget> hotWidget() {
    return controller.visitList
        .asMap()
        .map((index, e) => MapEntry(
            index,
            InkWell(
              onTap: () {
                Get.back(result: e.name);
              },
              child: Chip(
                label: Text(e.name),
                backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                side: BorderSide.none,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.w)),
                labelStyle:
                    StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 13.sp),
              ),
            )))
        .values
        .toList();
  }

  Widget buildHeader() {
    return Column(
      children: [
        Container(
          height: 30.h,
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(bottom: 5.h, left: 10.w, right: 10.w),
          child: Text(
            '当前位置',
            style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
          ),
        ),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 10.w),
          child: Row(
            children: [
              Container(
                constraints: BoxConstraints.expand(width: 107.w, height: 30.h),
                decoration: BoxDecoration(
                    color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7)),
                alignment: Alignment.center,
                child: Text.rich(TextSpan(children: [
                  WidgetSpan(
                      child: Icon(
                        Icons.place_rounded,
                        size: 20.w,
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478),
                      ),
                      alignment: PlaceholderAlignment.middle),
                  TextSpan(
                      text: ' ${controller.city.value}',
                      style: StylesUtils.customTextStyle(color: ColorsUtils.color0000))
                ])),
              )
            ],
          ),
        ),
        Container(
          height: 30.h,
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(bottom: 5.h, top: 5.h, left: 10.w, right: 10.w),
          child: Text(
            '经常访问',
            style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
          ),
        ),
        Container(
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(bottom: 5.h, left: 10.w, right: 10.w),
          child: Wrap(
            direction: Axis.horizontal,
            crossAxisAlignment: WrapCrossAlignment.center,
            spacing: 5.w,
            runSpacing: 10.w,
            children: hotWidget(),
          ),
        )
      ],
    );
  }

  Widget getListDataItem(BuildContext context, CityDataModel model) {
    List<CityModel> list = model.children ?? [];
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
      alignment: Alignment.centerLeft,
      child: Wrap(
        direction: Axis.horizontal,
        crossAxisAlignment: WrapCrossAlignment.center,
        spacing: 5.w,
        runSpacing: 10.w,
        children: list
            .map((e) => InkWell(
                  onTap: () {
                    Get.back(result: e.name);
                  },
                  child: Chip(
                    label: Text(e.name),
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                    side: BorderSide.none,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.w)),
                    labelStyle:
                        StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 13.sp),
                  ),
                ))
            .toList(),
      ),
    );
  }

  Widget getSusDataItem(BuildContext context, String tag, {required double susHeight}) {
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: 16.w),
      color: const Color(0xFFF3F4F5),
      alignment: Alignment.centerLeft,
      child: Text(tag,
          softWrap: false,
          style: StylesUtils.customTextStyle(
              color: ColorsUtils.color6666, fontSize: 16.sp, fontWeight: FontWeight.bold)),
    );
  }
}
